<?php

class ProductController extends SBaseController {

    public $layout = 'main';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * Displays a particular model.
     */
    public function actionView() {
        $this->layout = "detail";
        $this->render('view', array(
            'model' => $this->loadModel(),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Product();

        $model->status = Lvc::STATUS_ENABLED;
        $model->sorder = Common::getNewestPosition($model);
        $model->last_update = time();
        $model->hits = 0;
        $this->pageTitle = Yii::t('Global', 'Create') . Yii::t('BackEnd', 'product');
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        $seo = new Seo();
        if (isset($_POST['Product'])) {
            $model->attributes = $_POST['Product'];
            if ($model->validate()) {
                if ($model->insert()) {
                    //=========     Image   ==========//
                    $images = $_POST['imageRow'];
                    $imgDefault = $_POST['is_default'];
                    $imageIndex = $images['index'];
                    $hasDefault = false;
                    $tmpFolder = Common::getTmp();
                    $productImages = array();
                    for ($i = 0, $n = count($imageIndex); $i < $n; $i++) {
                        $imageFile = $_FILES['imageRow']['tmp_name'][$imageIndex[$i]]['file'];
                        if (!empty($imageFile)) {
                            $fileName = $_FILES['imageRow']['name'][$imageIndex[$i]]['file'];
                            $ext = substr($fileName, strrpos($fileName, '.'));
                            $tmpFile = $tmpFolder . time() . $ext;

                            $productImages[$i]['name'] = $images[$imageIndex[$i]]['name'];

                            $validateUpload = Common::uploadImageFromArray($_FILES['imageRow'], $imageIndex[$i], $tmpFile);
                            if ($validateUpload['code']) {
                                $sourceDir = $model->getImageDir();

                                $imageModel = new ProductImagePeer();
                                $imageModel->product_id = $model->id;
                                $imageModel->name = (!empty($productImages[$i]['name']) ? $productImages[$i]['name'] : $model->name);
                                $imageModel->file_name = $ext;
                                $imageModel->status = Lvc::STATUS_ENABLED;
                                $imageModel->insert();

                                //Resize to large image
                                $destFile = $sourceDir . DIRECTORY_SEPARATOR . $imageModel->id . '_large' . $ext;
                                $imageSize = Yii::app()->params['productImageSize']['large'];
                                Common::resize($tmpFile, $destFile, array('width' => $imageSize['w'], 'height' => $imageSize['h']));

                                //Resize to normal image
                                $destFile = $sourceDir . DIRECTORY_SEPARATOR . $imageModel->id . '_normal' . $ext;
                                Common::resize($tmpFile, $destFile, array('extend' => $ext));

                                //Resize to medium image
                                $destFile = $sourceDir . DIRECTORY_SEPARATOR . $imageModel->id . '_medium' . $ext;
                                $imageSize = Yii::app()->params['productImageSize']['medium'];
                                Common::resize($tmpFile, $destFile, array('width' => $imageSize['w'], 'height' => $imageSize['h']));

                                //Resize to small image
                                $destFile = $sourceDir . DIRECTORY_SEPARATOR . $imageModel->id . '_small' . $ext;
                                $imageSize = Yii::app()->params['productImageSize']['small'];
                                Common::resize($tmpFile, $destFile, array('width' => $imageSize['w'], 'height' => $imageSize['h']));

                                //Resize to small image
                                $destFile = $sourceDir . DIRECTORY_SEPARATOR . $imageModel->id . '_thumbnail' . $ext;
                                $imageSize = Yii::app()->params['productImageSize']['thumbnail'];
                                Common::resize($tmpFile, $destFile, array('width' => $imageSize['w'], 'height' => $imageSize['h']));
                            }
                            if (file_exists($tmpFile))
                                unlink($tmpFile);
                        }
                    }//End For
                    if($imageModel &&!$hasDefault) {
                        $imageModel->is_default = 1;
                        $imageModel->save();
                        $thumbnailFile = $sourceDir . DIRECTORY_SEPARATOR . $model->id . "_thumbnail" . $ext;
                        $thumbnailSize = Yii::app()->params['productImageSize']['thumbnail'];
                        Common::resize($sourceDir . DIRECTORY_SEPARATOR . $imageModel->id . "_normal" . $ext, $thumbnailFile, array('width' => $thumbnailSize['w'], 'height' => $thumbnailSize['h']));
                    }
                    unset($images);
                    //=========     Seo     ==========//
                    $seo->category = Common::PRODUCT;
                    $seo->record_url = $model->url_key;
                    $seo->title = $model->product_name;
                    $seo->keyword = $model->product_name;
                    $seo->description = $model->description;
                    $seo->status = Lvc::STATUS_ENABLED;
                    $seo->insert();

                    Yii::app()->user->setFlash('message', Yii::t('Global', 'Create successfully.'));
                    $this->redirect(array('view', 'id' => $model->id));
                }
            }
        }
        $seo->status = Lvc::STATUS_ENABLED;
        $seo->category = Common::PRODUCT;
        $this->layout = "detail";
        $this->render('create', array(
            'model' => $model,
            'seo' => $seo
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     */
    public function actionUpdate() {
        $model = $this->loadModel();

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        $this->pageTitle = Yii::t('Global', 'Create') . Yii::t('BackEnd', 'product');

        if (isset($_POST['Product'])) {
            $model->attributes = $_POST['Product'];
            if ($model->validate()) {
                if ($model->update()) {
                    Product::model()->rebuildSOrder();
                    Yii::app()->user->setFlash('message', Yii::t('Global', 'Update successfully.'));
                    $this->redirect(array('view', 'id' => $model->id));
                }
            }
        }

        $this->layout = "detail";
        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     */
    public function actionDelete() {
        if (isset($_POST['select-row']) && is_array($_POST['select-row'])) {
            $ids = $_POST['select-row'];
            $ids = implode(',', $ids);
            Product::model()->deleteAll("id in ($ids)");
            $this->redirect(array('admin'));
        } elseif (Yii::app()->request->isPostRequest) {
            $model = $this->loadModel();
            $model->delete();
            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        if (!isset($_GET['ajax']) && isset($_POST['sorder'])) {
            $ids = $_POST['ids'];
            $sorder = $_POST['sorder'];
            for ($i = 0; $i < count($ids); $i++) {
                $model = Product::model()->findByPk($ids[$i]);
                $model->sorder = $sorder[$i];
                $model->save();
            }
            Product::model()->rebuildSOrder();
            Yii::app()->user->setFlash('message', Yii::t('Global', 'Update successfully.'));
        }

        $this->pageTitle = Yii::t('Global', 'Manage') . Yii::t('BackEnd', 'product');
        $model = new Product('search');
        if (isset($_GET['Product']))
            $model->attributes = $_GET['Product'];

        $this->layout = "list";
        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel() {
        if ($this->_model === null) {
            if (isset($_GET['id']))
                $this->_model = Product::model()->findbyPk($_GET['id']);
            if ($this->_model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $this->_model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'product-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionChangeStatus() {
        if ($_POST['ajax'] && $_POST['id']) {
            $model = Product::model()->findByPk($_POST['id']);
            if ($model->status == Lvc::STATUS_ENABLED)
                $model->status = Lvc::STATUS_DISABLED;
            elseif ($model->status == Lvc::STATUS_DISABLED)
                $model->status = Lvc::STATUS_ENABLED;
            $model->save();
            Yii::app()->end();
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    public function actionCheckName() {
        if (Yii::app()->request->isPostRequest) {
            $id = Lvc::selectOne(Product::model()->tableName(), 'id', 'product_name="' . $_POST['name'] . '" ');
            if ($id) {
                $array = array(
                    "success" => true,
                    'link' => '<a href="' . Yii::app()->createUrl('Product/view', array('id' => $id['id'])) . '" >' . Yii::t('BackEnd', 'Name exit.') . '</a> '
                );
                echo json_encode($array);
            }
            else
                echo '{"success":false}';
            Yii::app()->end();
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    public function actionTagsList() {
        $q = $_GET['term'];
        $systemMinCharSearch = isset(Yii::app()->params->systemMinCharSearch) ? Yii::app()->params->systemMinCharSearch : 1;
        if (isset($q) && strlen($q) >= $systemMinCharSearch) {
            $criterial = new CDbCriteria();
            $criterial->select = "DISTINCT(tagged)";
            $criterial->addCondition('status =' . Lvc::STATUS_ENABLED, 'AND');
            $criterial->addCondition("tagged != ''", 'AND');
            $criterial->order = "tagged";
            $tags = Product::model()->findAll($criterial);
            $q = strtolower($q);
            $result = array();
            if ($tags) {
                $arrayCheck = array();
                $count = 1;
                foreach ($tags as $tag) {
                    $tag = explode(',', $tag->tagged);
                    $total_tags = count($tag);
                    for ($i = 0; $i < $total_tags; $i++) {
                        $tagEdit = trim($tag[$i]);
                        if (!in_array($tagEdit, $arrayCheck) && strtolower(substr($tagEdit, 0, strlen($q))) == $q) {
                            $result[] = '{"id":"' . $count . '-' . $i . '","label":"' . $tagEdit . '","value":"' . $tagEdit . '"}';
                            array_push($arrayCheck, $tagEdit);
                        }
                    }
                    $count++;
                }
            }
            echo "[" . implode(',', $result) . "]";
        }
        Yii::app()->end();
    }

}
